<template>
  <div class="h-full flex flex-col">
    <!-- 搜索框 -->
    <div class="p-4">
      <el-input v-model="searchText" placeholder="搜索会话" :prefix-icon="Search" clearable />
    </div>

    <!-- 会话列表 -->
    <div class="flex-1 overflow-y-auto">
      <el-empty v-if="!loading && filteredSessions.length === 0" description="暂无会话" />
      <el-skeleton v-else-if="loading" :rows="3" animated class="p-4" />
      <template v-else>
        <session-item v-for="session in filteredSessions" :key="session.id" :session="session"
          :active-id="currentSessionId" @click="handleSessionClick" />
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { useChatSessionStore } from '@/stores/useChatSessionStore'
import type { ChatSessionResponse } from '@/types'
import SessionItem from './SessionItem.vue'

const router = useRouter()
const chatSessionStore = useChatSessionStore()
const { sortedSessions, currentSessionId, loading } = storeToRefs(chatSessionStore)

const searchText = ref('')

// 过滤后的会话列表
const filteredSessions = computed(() => {
  if (!searchText.value) return sortedSessions.value
  const keyword = searchText.value.toLowerCase()
  return sortedSessions.value.filter(session =>
    session.targetName.toLowerCase().includes(keyword) ||
    (session.lastMessage && session.lastMessage.toLowerCase().includes(keyword))
  )
})

// 处理会话点击
const handleSessionClick = (session: ChatSessionResponse) => {
  chatSessionStore.currentSessionId = session.id
  // 标记会话已读
  
  // 导航到聊天详情页面
  router.push({
    name: 'chat-detail',
    params: { id: session.id }
  })
}

// 加载会话列表
onMounted(() => {
  chatSessionStore.loadSessions()
})
</script>